package com.fu.core.util;

import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;

import java.nio.charset.Charset;
import java.util.HashSet;
import java.util.Set;

/**
 * @author 付龙江
 * @date 2022/1/27 21:42
 */
public class RedisUtil {

    /**
     * 查询时候含有该值的前100条keys,参数mes注入用比如"goodsDetailInfo:"+"*"
     * @param mes
     * @return
     */
    public static Set<String> getKeys(String mes,RedisTemplate<String ,Object> redisTemplate){
        RedisCallback<Set<String>> setRedisCallback = new RedisCallback<Set<String>>(){
            @Override
            public Set<String> doInRedis(RedisConnection connection) throws DataAccessException {
                Set<String> resultSet = new HashSet<>();
                //COUNT为1000表示提示hint此次需要返回1000个数据，但实际并不一定，可能更多也可能更少。在多次迭代中COUNT可以指定不同的值。COUNT默认值为10.
                ScanOptions build = ScanOptions.scanOptions().match(mes).count(1000).build();
                Cursor<byte[]> cursor = connection.scan(build);
                while (cursor.hasNext()) {
                    byte[] next = cursor.next();
                    //byte形式转化成字符串
                    String s = new String(next, Charset.defaultCharset());
                    resultSet.add(s);
                }
                return resultSet;
            }
        };
        Set<String> execute = redisTemplate.execute(setRedisCallback);
        return execute;
    }
}
